// Includes
#include "MeshViewer.h"

#include <iostream>			// C++ I/O stream library
#include <SDL/SDL.h>		// SDL main header

using namespace std;

namespace EraAstral
{
	using namespace core;
	using namespace graphics;

	namespace tools
	{
		// Mesh viewer class default constructor
		MeshViewer::MeshViewer()
		{
			// Set null pointers
			m_device = NULL;
			m_mesh = NULL;
			m_eventHandler = NULL;
			m_input = NULL;
			
			m_shouldRun = true;
			
			// Create graphics device
			m_device = graphics::CreateDevice(NULL);
			
			// Check for error
			if (!m_device)
			{
				// Print error
				cout << "Error creating graphics device." << endl;
			}
			else
			{
				// Graphics device created successfully
				
				// Set window caption
				SDL_WM_SetCaption("Era Astral - Mesh Viewer", NULL);
				
				// Create other components
				m_eventHandler = new EventHandler();
				m_input = new InputDevice();
				// Register objects with event handler
				m_eventHandler->RegisterAffectedObject(this);
				m_eventHandler->RegisterAffectedObject(m_input);
			}
		}
		
		// Mesh viewer class default destructor
		MeshViewer::~MeshViewer()
		{
			// Delete mesh
			if (m_mesh != NULL)
				delete m_mesh;		
		
			// Delete graphics device
			if (m_device != NULL)
				delete m_device;
				
			// Delete input device
			if (m_input != NULL)
				delete m_input;
				
			// Delete event handler
			if (m_eventHandler != NULL)
				delete m_eventHandler;
		}
		
		// Runs the mesh viewer
		void MeshViewer::Run()
		{
			// Program kernel
			while (m_shouldRun)
			{
				// Process events
				m_eventHandler->ProcessEvents();			
			
				// Begin frame
				m_device->BeginFrame();			
			
				// Draw the mesh
				if (m_mesh != NULL)
					m_mesh->Draw();
					
				// End frame
				m_device->EndFrame();
			}
		}
		
		// Exits the mesh viewer
		void MeshViewer::Exit()
		{
			// Clear kernel flag
			m_shouldRun = false;
		}
		
		// Process events
		void MeshViewer::ProcessEventSignal(const Event *event)
		{
			// Exit on quit signal
			if (event->type == EVENT_QUIT)
				Exit();
		}
	}
}